package design_pattern.immutableMode;

import java.util.stream.IntStream;

/**
 * @Author: 蔡翔
 * @Date: 2019/11/6 11:00
 * @Version 1.0
 *
 * 不可变对象可以提升 性能(但是差距不大，主要是对synchronize 优化很多。)
 * 不可变对象：38713
 * 可变对象 ：37941
 */
public class ImmutablePerformance {
    public static void main(String[] args) {
        // 不可变对象
        long startTimestamp = System.currentTimeMillis();
        ImmutableObj syncObj = new ImmutableObj("cx");
        IntStream.range(0,2).forEach(s->new Thread(()->{
            for(long l=0L;l<10000000;l++){
                System.out.println(Thread.currentThread().getName()+"="+ syncObj.toString());
            }
        }).start());
        long endTimeStamp = System.currentTimeMillis();
        System.out.println("Elapsed time"+(endTimeStamp-startTimestamp));
    }
}
//不可变对象
class ImmutableObj{
    private final String name;
    public ImmutableObj(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "["+ name +"]";
    }
}

//可变对象
class SyncObj{
    private String name;
    public synchronized void setName(String name){
        this.name = name;
    }
    @Override
    public String toString() {
        return "["+ name +"]";
    }
}